package com.example.demo1;

import com.example.demo1.bean.Point;
import com.example.demo1.bean.PointDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PointController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    JdbcTemplate subJdbcTemplate;

    @ResponseBody
    @RequestMapping(value = "savePoint", method = RequestMethod.POST)
    private String saveInfo(HttpServletRequest req, @RequestParam(required = false) MultipartFile[] files,String longtitude,String latitude,String phonenumber,String idCard,String currentLocation,int admin,String geometry){
//        String filepath = "";
        String sql = "insert into pointTable(longtitude,latitude,phonenumber,idCard,currentLocation,geometry,admin) values(?,?,?,?,?,?,?) ";

        int index = jdbcTemplate.update(sql,longtitude,latitude,phonenumber,idCard,currentLocation,geometry,admin);
        String sql_lastData = "select id from pointTable ORDER BY id DESC limit 1";
        int lastId = jdbcTemplate.queryForObject(sql_lastData,Integer.class);
        if (files != null && files.length > 0){
            for(int i = 0;i<files.length;i++){
                MultipartFile file = files[i];
                try {
                    //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
                    String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                    //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
//                    String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
                    String destFileName =  "/Users/geowin/workspace/temp-rainy" + File.separator + fileName;
                    //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）

                    File destFile = new File(destFileName);
                    destFile.getParentFile().mkdirs();
                    //5.把浏览器上传的文件复制到希望的位置
                    file.transferTo(destFile);
                    //6.把文件名放在model里，以便后续显示用
                    String filePath_Sql = "insert into point_file(imageindex,filepath) values(?,?)";
                    jdbcTemplate.update(filePath_Sql,lastId  ,fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return "上传失败," + e.getMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                    return "上传失败," + e.getMessage();
                }
            }
        }

        if (index == 1)
            return "success";
        else
            return "false";
    }

    @RequestMapping(value = "queryAll")
    private List<PointDao> queryAllData(int type){
//        List<Map<String,Object>> listData;
        String sql;
        if (type == 0){
//            "SELECT * from pointTable LEFT  JOIN point_file ON pointTable.id  = point_file.imageindex;";
            sql = "SELECT * from pointTable LEFT  JOIN point_file ON pointTable.id  = point_file.imageindex";
        }else{
            sql  = "select * from (select * from pointTable WHERE pointTable.admin = "+(type-1) +") as A  LEFT JOIN point_file ON A.Id = point_file.imageindex";
        }


        System.out.println("查询所有的数据: " +sql);

//        listData =  jdbcTemplate.queryForList(sql,PointDao.class);

        List<PointDao> points = new ArrayList<PointDao>();
        jdbcTemplate.query(sql, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                    PointDao pointDao = new PointDao();
                    String id = resultSet.getString("id");
                    pointDao.setId(id);
                    pointDao.setLongtitude(resultSet.getFloat("longtitude"));
                    pointDao.setLatitude(resultSet.getFloat("latitude"));
                    pointDao.setIdCard(resultSet.getString("idCard"));
                    pointDao.setAdmin(resultSet.getInt("admin"));
                    pointDao.setCurrentLocation(resultSet.getString("currentLocation"));
                    pointDao.setPhonenumber(resultSet.getString("phonenumber"));
                    pointDao.setGeometry(resultSet.getString("geometry"));
                    String filepath = resultSet.getString("filepath");
                    List<String> paths = new ArrayList<>();
                    try {
                        if (filepath != null && filepath.length() != 0){
                            paths.add(filepath);
                            pointDao.setFilepath(paths);
                        }
                    }catch (NullPointerException e){
                        e.printStackTrace();
                    }
                    int index = getListExistIndex(pointDao,points);
                    if(index == -1){
                        points.add(pointDao);
                    }else{
                        PointDao subPoint = points.get(index);
                        if (filepath.length() != 0){
                            subPoint.getFilepath().add(filepath);
                        }

                    }
            }
        });

        return points;
    }

    public int getListExistIndex(PointDao point,List<PointDao> points){
        if (points == null || points.size() == 0) return  -1;
        for(int i = 0;i<points.size();i++){
            PointDao subPoint = points.get(i);
            if (subPoint.getId().equals(point.getId())){
                return  i;
            }
        }
        return  -1;
    }


    @RequestMapping(value = "queryS")
    private List<PointDao> queryS(String text){
//        List<Map<String,Object>> listData;

        String sql;
        if (text == null ||text.isEmpty() || text.length() == 0){
            sql = "select * from pointTable   WHERE admin=0  limit 10 ";
        }else{
           sql = "Select * from pointTable where currentLocation and admin = 0 like'%"+ text+"%' limit 10";
        }

//        listData =  jdbcTemplate.queryForList(sql,PointDao.class);

        List points = new ArrayList();
        System.out.println("-----------------"+sql);
        jdbcTemplate.query(sql, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                PointDao pointDao = new PointDao();
                pointDao.setLongtitude(resultSet.getFloat("longtitude"));
                pointDao.setLatitude(resultSet.getFloat("latitude"));
                pointDao.setId(resultSet.getString("id"));
                pointDao.setIdCard(resultSet.getString("idCard"));
                pointDao.setAdmin(resultSet.getInt("admin"));
                pointDao.setCurrentLocation(resultSet.getString("currentLocation"));
                pointDao.setPhonenumber(resultSet.getString("phonenumber"));
                points.add(pointDao);
            }
        });

        return points;
    }




    @RequestMapping("/query")
    public Map<String,Object>  queryData(){
        Map<String,Object> map = new HashMap<String,Object>(15);
        String sql = "Select * from pointTable WHERE admin=0 limit 10";
        try{
            map = jdbcTemplate.queryForMap(sql);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
        return map;
    }


    @RequestMapping(value = "queryPoint")
    private PointDao queryPointInfo(String id){
        if (id == null){
            return null;
        }
        PointDao point = new PointDao();
        point.setAdmin(1);
        point.setId(id);
        point.setIdCard("1256243");
        point.setLatitude(102.12312f);
        point.setLongtitude(101.13213f);
        return point;
    }

    @RequestMapping(value = "deletePoint")
    private String delete(int id){
        String sql = "delete from pointTable where id =  " + id;
        String sql2 = "delete from point_file where imageindex = " + id;
        jdbcTemplate.update(sql);
        jdbcTemplate.update(sql2);
        return "success";
    }



    @RequestMapping(value = "chaxun")
    private PointDao getDao(){
        PointDao point = new PointDao();
        point.setAdmin(1);
        point.setId("1");
        point.setIdCard("1256243");
        point.setLatitude(102.12312f);
        point.setLongtitude(101.13213f);
        return point;
    }

    @RequestMapping(value = "select",method = RequestMethod.GET)
    private String getPoint(){
        String sql = "SELECT phonenumber FROM pointTable WHERE id  = ?";
        String mobile = (String)jdbcTemplate.queryForObject(
                sql, new Object[] { 1 }, String.class);

        return "hello " + mobile;
    }


    @ResponseBody
    @RequestMapping("/icon")
    public String saveIcon(@RequestParam MultipartFile icon, HttpSession session)
            throws Exception {

        if (icon.getSize() > 0) {
            String path = session.getServletContext().getRealPath("/images");
            String fileName = icon.getOriginalFilename();
            File file = new File(path, fileName);
            icon.transferTo(file);
            //------其他数据库操作省略------
            return  "success";
//            return Msg.success(null);
        }
        return "Msg.fail()";
    }


//    @PostMapping("upload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    public String upload(HttpServletRequest req, @RequestPart("file") MultipartFile file, @RequestParam(value = "point",required = false) Point point) {//1. 接受上传的文件  @RequestParam("file") MultipartFile file
//        try {
//            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
//            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
//            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
//            String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
//            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
//            File destFile = new File(destFileName);
//            destFile.getParentFile().mkdirs();
//            //5.把浏览器上传的文件复制到希望的位置
//            file.transferTo(destFile);
//            //6.把文件名放在model里，以便后续显示用
////            m.addAttribute("fileName", fileName);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            return "上传失败," + e.getMessage();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "上传失败," + e.getMessage();
//        }
//
//        return "showImg";
//    }


    @PostMapping("upload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest req, @RequestPart("file") MultipartFile file) {//1. 接受上传的文件  @RequestParam("file") MultipartFile file
        try {
            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
            String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
            //6.把文件名放在model里，以便后续显示用
//            m.addAttribute("fileName", fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }

        return "showImg";
    }



    // 上传多个文件
    @ResponseBody
    @RequestMapping(value="/uploadMore",method=RequestMethod.POST)
    public String uptestMost(@RequestParam MultipartFile[] files, @RequestParam String number,HttpSession session) throws Exception {
        String path = session.getServletContext().getRealPath("/images");
        for (MultipartFile img : files) {
            if (img.getSize() > 0) {
                String fileName = img.getOriginalFilename();
                File file = new File(path, fileName);
                img.transferTo(file);
                return "Msg.success(null)";
            }
        }
        return "Msg.fail()";
    }




}
